<?php
declare (strict_types = 1);

namespace app\admin\service;

use think\Log;
use think\Config;

/**
 * 数脉API服务类
 */
class ShumaiApiService
{
    /**
     * 数脉API基础URL
     * @var string
     */
    protected $baseUrl = 'https://api.shumaidata.com/v4';
    
    /**
     * 应用ID
     * @var string
     */
    protected $appId;
    
    /**
     * 应用安全密钥
     * @var string
     */
    protected $appSecurity;
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        // 从配置文件中获取API凭据
        $this->appId = Config::get('third_party.shumai.app_id', '');
        $this->appSecurity = Config::get('third_party.shumai.app_security', '');
        
        if (empty($this->appId) || empty($this->appSecurity)) {
            Log::error('数脉API配置缺失，请检查配置文件');
        }
    }
    
    /**
     * 身份证实名认证
     * 
     * @param string $name 姓名
     * @param string $idCard 身份证号
     * @return array 验证结果
     */
    public function verifyIdentity($name, $idCard)
    {
        $url = $this->baseUrl . '/person_car/check';
        $timestamp = time();
        
        $params = [
            'appid' => $this->appId,
            'timestamp' => $timestamp,
            'sign' => $this->generateSign($timestamp),
            'name' => $name,
            'idcard' => $idCard
        ];
        
        $result = $this->sendRequest($url, $params);
        
        // 记录日志
        Log::info('身份证实名认证请求', [
            'name' => $name,
            'id_card' => substr($idCard, 0, 6) . '******' . substr($idCard, -4),
            'result' => isset($result['code']) ? $result['code'] : 'unknown'
        ]);
        
        return $result;
    }
    
    /**
     * 人车核验
     * 
     * @param string $name 姓名
     * @param string $carNo 车牌号
     * @param string $carColor 车牌颜色（0:蓝色 1:黄色 2:黑色 3:白色 4:渐变绿色 5:黄绿双拼色 6:蓝白渐变色 7:临时牌照 11:绿色 12:红色）
     * @return array 验证结果
     */
    public function verifyVehicle($name, $carNo, $carColor = '0')
    {
        $url = $this->baseUrl . '/person_car/check';
        $timestamp = time();
        
        $params = [
            'appid' => $this->appId,
            'timestamp' => $timestamp,
            'sign' => $this->generateSign($timestamp),
            'name' => $name,
            'carNo' => $carNo,
            'carColor' => $carColor
        ];
        
        $result = $this->sendRequest($url, $params);
        
        // 记录日志
        Log::info('人车核验请求', [
            'name' => $name,
            'car_no' => $carNo,
            'car_color' => $carColor,
            'result' => isset($result['code']) ? $result['code'] : 'unknown'
        ]);
        
        return $result;
    }
    
    /**
     * 生成签名
     * 
     * @param int $timestamp 时间戳
     * @return string 签名
     */
    protected function generateSign($timestamp)
    {
        // 按照数脉API文档，签名算法为：md5(appid + timestamp + app_security)
        $signStr = $this->appId . $timestamp . $this->appSecurity;
        return md5($signStr);
    }
    
    /**
     * 发送API请求
     * 
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @return array 响应数据
     */
    protected function sendRequest($url, $params)
    {
        try {
            $ch = curl_init();
            
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            
            curl_close($ch);
            
            if ($error) {
                Log::error('数脉API请求失败', ['url' => $url, 'error' => $error]);
                return [
                    'code' => -1,
                    'msg' => '网络请求失败: ' . $error,
                    'data' => null
                ];
            }
            
            if ($httpCode != 200) {
                Log::error('数脉API响应异常', ['url' => $url, 'http_code' => $httpCode, 'response' => $response]);
                return [
                    'code' => -1,
                    'msg' => '服务响应异常，状态码: ' . $httpCode,
                    'data' => null
                ];
            }
            
            $result = json_decode($response, true);
            
            if (!$result) {
                Log::error('数脉API响应解析失败', ['url' => $url, 'response' => $response]);
                return [
                    'code' => -1,
                    'msg' => '响应数据解析失败',
                    'data' => null
                ];
            }
            
            return $result;
            
        } catch (\Exception $e) {
            Log::error('数脉API请求异常', ['url' => $url, 'exception' => $e->getMessage()]);
            return [
                'code' => -1,
                'msg' => '请求异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
}
